<template>
<el-dialog :title="couponids==-1?'新增优惠券':'编辑优惠券'" :visible.sync="open" :before-close="close" append-to-body>
    <goodslist @getgoodsid="getgooditem"/>
    <el-form :model="f" :rules="rules" ref="CouponForm" class="dialogh">
        <el-form-item label="优惠券名称" class="is-required" :label-width="formLabelWidth" prop="couponName">
            <el-input v-model="f.couponName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="领取时间" :label-width="formLabelWidth" prop="receiveTimeValue">
            <el-date-picker
                    v-model="receiveTimeValue"
                    type="datetimerange"
                    placeholder="选择时间范围">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="金额类型" :label-width="formLabelWidth" prop="priceType">
            <el-radio-group v-model="f.priceType">
                <el-radio-button :label='0'>固定</el-radio-button>
                <el-radio-button :label='1'>随机</el-radio-button>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="优惠金额" class="is-required" :label-width="formLabelWidth" prop="couponPrice">
            <el-input v-model.number="f.couponPrice" auto-complete="off" style="width: 100px;margin-right: 10px"></el-input>元
        </el-form-item>
        <el-form-item label="满减条件" class="is-required" :label-width="formLabelWidth" prop="fullPrice">
            满<el-input v-model.number="f.fullPrice" auto-complete="off" style="width: 100px;margin: 0 10px"></el-input>元可用
        </el-form-item>
        <el-form-item label="发行数量" class="is-required" :label-width="formLabelWidth" prop="totalCount">
            <el-input v-model.number="f.totalCount" auto-complete="off" style="width: 100px;margin-right: 10px"></el-input>张
        </el-form-item>
        <el-form-item label="优惠券类型" :label-width="formLabelWidth" prop="scopeType">
            <el-radio-group v-model="f.scopeType">
                <el-radio-button :label='1'>范围优惠券</el-radio-button>
                <el-radio-button :label='2'>时长优惠券</el-radio-button>
                <el-radio-button :label='3'>运费优惠券</el-radio-button>
            </el-radio-group>
        </el-form-item>
        <el-form-item v-if="f.scopeType == 1" label="使用时间" :label-width="formLabelWidth">
            <el-date-picker
                    v-model="useTimeValue"
                    type="datetimerange"
                    placeholder="选择时间范围">
            </el-date-picker>
        </el-form-item>
        <el-form-item v-if="f.scopeType == 2" label="使用时长" :label-width="formLabelWidth">
            <el-input v-model="f.durationDay" auto-complete="off" style="width: 100px;margin-right: 10px"></el-input>天
        </el-form-item>
        <el-form-item v-if="f.scopeType == 3" label="使用时间" :label-width="formLabelWidth">
            <el-date-picker
                v-model="receiveTimeValue2"
                type="datetimerange"
                placeholder="选择时间范围">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="是否发布" :label-width="formLabelWidth" prop="status">
            <el-radio-group v-model="f.status">
                <el-radio-button :label='1'>发布</el-radio-button>
                <el-radio-button :label='0'>不发布</el-radio-button>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="使用类型" :label-width="formLabelWidth" prop="useType">
            <el-radio-group v-model="f.useType">
                <el-radio-button :label='0'>全部商品</el-radio-button>
                <el-radio-button :label='1'>指定商品</el-radio-button>
            </el-radio-group>
        </el-form-item>
        <el-form-item v-if="f.useType == 1" label="指定商品" :label-width="formLabelWidth">
            <div class="inner-line-item">
                <el-input v-model="f.canUseId" disabled style="width: 100px"></el-input>
                <el-button @click="chooseCouponGoods" class="inner-line-item-button">选择指定商品</el-button>
            </div>
        </el-form-item>
        <el-form-item label="优惠券缩略图" :label-width="formLabelWidth">
            <el-upload drag
                action="http://up-z0.qiniu.com"
                :data="uploadData"
                :file-list="fileDetailUploadList"
                :on-success="handleDetailUploadSuccess"
                :on-remove="handleDetailRemove"
                :on-error="handleUploadError"
                :before-upload="handleBeforUpload"
                list-type="picture-card">
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
        </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
        <el-button @click="close()">取 消</el-button>
        <el-button type="primary" @click="save()">确 定</el-button>
    </div>
</el-dialog>
</template>
<script>
import goodslist from 'components/goodslist'
import moment from 'moment'
export default {
    data(){
        return {
            open:false,
            formLabelWidth:'120px',
            receiveTimeValue:[],
            receiveTimeValue2:[],
            useTimeValue:[],
            uploadData: {
                key: '',
                token: ''
            },
            fileDetailUploadList:[],
            f:{
                couponName:'',
                scopeType:'1',
                receiveBeginTime:'',
                receiveEndTime:'',
                useBeginTime:'',
                useEndTime:'',
                durationDay:'',
                fullPrice:'',
                couponPrice:'',
                totalCount:'',
                status:'1',
                priceType:'0',
                useType:'0',
                canUseId:''
            },
            // rules:{
            //     couponName: [
            //         { required: true, message: '请输入优惠券名称', trigger: 'blur' }
            //     ],
            //     totalCount: [
            //         { required: true, message: '请输入优惠券数量'},
            //         { type: 'number',  message: '数量必须是数字', trigger: 'blur' }
            //     ],
            //     couponPrice: [
            //         { required: true, message: '请输入优惠金额'},
            //         { type: 'number',  message: '金额必须是数字', trigger: 'blur' }
            //     ],
            //     fullPrice: [
            //         { required: true, message: '请输入满减金额'},
            //         { type: 'number',  message: '金额必须是数字', trigger: 'blur' }
            //     ]
            // },
            couponids:-1
        }
    },
    components:{
        goodslist
    },
    computed:{
        getstate(){
            return this.$store.state.coulistclass;
        },
        getval(){
            return this.$store.state.coulist;
        }
    },
    watch:{
        getstate(v){//监听弹窗打开
            this.open=v
        },
        getval(v){//获取入参
            if(v.couponId){
                var x=this.f
                x.couponName=v.couponName
                this.receiveTimeValue=[new Date(v.receiveBeginTime),new Date(v.receiveEndTime)]
                x.priceType=v.priceType
                x.couponPrice=v.couponPrice
                x.fullPrice=v.fullPrice
                x.totalCount=v.totalCount
                x.scopeType=v.scopeType
                if(v.scopeType==1){
                    this.useTimeValue=[new Date(v.useBeginTime),new Date(v.useEndTime)]
                }else if(v.scopeType==3){
                    this.receiveTimeValue2=[new Date(v.useBeginTime),new Date(v.useEndTime)]
                }
                x.durationDay=v.durationDay
                x.status=v.status
                x.useType=v.useType
                x.canUseId=v.canUseId
                this.fileDetailUploadList=[]
                this.fileDetailUploadList.push({
                    name: '',
                    url: v.image
                })
                this.couponids=v.couponId
            }
        }
    },
    methods:{
        qiniuyunup(_vm, file, rule) {//图片上传
            const isJPG = file.type === 'image/jpeg'
            const isPNG = file.type === 'image/png'
            const isFitSize = rule.maxSize ? file.size / 1024 / 1024 < rule.maxSize : 'undefined';
            if (rule.isJPG || rule.isPNG) {
                if (!isJPG && !isPNG) {
                    _vm.$message.error('图片只能是 JPG/PNG 格式!');
                    return false
                }
            }
            if (isFitSize != 'undefined' && !isFitSize) {
                _vm.$message.error('大小不能超过 ' + rule.maxSize + 'MB!');
                return false
            }
        },
        handleDetailUploadSuccess(response, file, fileList) {//图片上传成功
            var newFile = {
                name: file.name,
                url: window.qiniuHost + response.key
            }
            this.fileDetailUploadList = []
            this.fileDetailUploadList.push(newFile)
        },
        handleDetailRemove(){//图片清空
            this.fileDetailUploadList = []
        },
        handleUploadError(error, file, fileList) {//图片上传失败
            const _this = this
            _this.$message.error('上传失败')
        },
        handleBeforUpload(file) {//图片上传前验证
            // console.log("file",file)
            const _this = this
            let rule = {
                isJPG: true,
                isPNG: true,
                maxSize: 2
            }
            var suffix = file.name.split('.')
            this.uploadData.key = new Date().getTime() + '.' + suffix[1]
            this.uploadData.token = this.$store.state.qiniuToken
            return this.qiniuyunup(_this, file, rule)
        },
        close(){
            this.f={
                couponName:'',
                scopeType:'1',
                receiveBeginTime:'',
                receiveEndTime:'',
                useBeginTime:'',
                useEndTime:'',
                durationDay:'',
                fullPrice:'',
                couponPrice:'',
                totalCount:'',
                status:'1',
                priceType:'0',
                useType:'0',
                canUseId:''
            }
            this.receiveTimeValue=[]
            this.receiveTimeValue2=[]
            this.fileDetailUploadList=[]
            this.useTimeValue=[]
            this.couponids=-1
            this.$store.state.coulistclass=false
            this.$store.state.coulist={}
        },
        save(){//保存
            var _this=this
            var pp=new URLSearchParams()
            // console.log(this.f.couponName)
            if(!this.f.couponName){
                this.$message.error("请填写优惠券名称")
                return
            }
            pp.append('couponName',this.f.couponName)
            pp.append('scopeType',this.f.scopeType)
            if(this.receiveTimeValue.length<1){
                this.$message.error("请填写领取时间")
                return
            }
            // console.log(moment(this.receiveTimeValue[0]).format("YYYY-MM-DD HH:mm:ss"),this.receiveTimeValue)
            pp.append('receiveBeginTime',moment(this.receiveTimeValue[0]).format("YYYY-MM-DD HH:mm:ss"))
            pp.append('receiveEndTime',moment(this.receiveTimeValue[1]).format("YYYY-MM-DD HH:mm:ss"))

            if(this.f.scopeType==1){
                if(this.useTimeValue.length<1){
                    this.$message.error("请填写使用时间")
                    return
                }
                pp.append('useBeginTime',moment(this.useTimeValue[0]).format("YYYY-MM-DD HH:mm:ss"))
                pp.append('useEndTime',moment(this.useTimeValue[1]).format("YYYY-MM-DD HH:mm:ss"))
            }
            if(this.f.scopeType==2){
                pp.append('durationDay',this.f.durationDay)
            }
            if(this.f.scopeType==3){
                if(this.receiveTimeValue2.length<1){
                    this.$message.error("请填写使用时间")
                    return
                }
                pp.append('useBeginTime',moment(this.receiveTimeValue2[0]).format("YYYY-MM-DD HH:mm:ss"))
                pp.append('useEndTime',moment(this.receiveTimeValue2[1]).format("YYYY-MM-DD HH:mm:ss"))
            }
            if(!this.f.fullPrice){
                this.$message.error("请填写满减条件")
                return
            }
            pp.append('fullPrice',this.f.fullPrice)
            if(!this.f.couponPrice){
                this.$message.error("请填写优惠金额")
                return
            }
            pp.append('couponPrice',this.f.couponPrice)
            if(!this.f.totalCount){
                this.$message.error("请填写发行数量")
                return
            }
            pp.append('totalCount',this.f.totalCount)
            pp.append('priceType',this.f.priceType)
            pp.append('status',this.f.status)
            if(this.fileDetailUploadList.length==0){
                this.$message.error("请上传优惠券缩略图")
                return
            }
            pp.append('image',this.fileDetailUploadList[0].url)
            pp.append('useType',this.f.useType)
            if(this.f.useType==1){
                pp.append('canUseId',this.f.canUseId)
            }
            if(this.couponids==-1){//新增
                axios.get('/saveCoupon.do',{params:pp}).then(r=>{
                    if(r.data.code==200){
                        _this.$message.success('新增成功')
                        _this.$store.state.closecoulistdialog=false
                        _this.$store.state.coulistnew=false
                        _this.$store.state.coulist={}
                        _this.close()
                    }else{
                        _this.$message.error(r.data.message)
                    }
                })
            }else{
                pp.append('couponId',this.couponids)
                axios.get('/updateCoupon.do',{params:pp}).then(r=>{
                    if(r.data.code==200){
                        _this.$message.success('修改成功')
                        _this.$store.state.closecoulistdialog=false
                        _this.$store.state.coulistnew=false
                        _this.$store.state.coulist={}
                        _this.close()
                    }else{
                        _this.$message.error(r.data.message)
                    }
                })
            }
        },
        chooseCouponGoods(){//打开商品选择的弹窗
            this.$store.commit('ChangeWxGood')
        },
        getgooditem(m){//获取数据
            this.f.canUseId=0
            this.f.canUseId=m
        }
    }
}
</script>
<style>
.el-dialog__header {
    padding: 10px;
    background-color: #20a0ff!important;
}
.dialogh{
    height: 600px;
    overflow: scroll;
}
</style>
